import json
import copy
import time
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *
import logging
import pandas as pd
import requests

check_tags_api = Blueprint('check_tags_api', __name__)


@check_tags_api.route('/check_tags', methods=['POST'])
def check_tags():
    params = json.loads(request.data)

    _action = params['action']
    _event_type = params['event_type']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        query = CheckTags.query.all()
        result = []
        for q in query:
            tmp = {
                "event_type": int(q.event_type),
                'tags': json.loads(q.tags)
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'update':
        _tags = params['tags']
        project_data = CheckTags.query.filter_by(event_type=_event_type).first()
        project_data.tags = json.dumps(_tags)
        db.session.commit()
    elif _action == 'get_usage_list':
        result = {}
        with open(STATIC_PATH + 'check_tags/event_list.json', encoding='UTF-8') as f:
            event_list = json.load(f)
        if str(_event_type) not in event_list:
            return json.dumps({})

        query = CheckTags.query.filter_by(event_type=_event_type).first()
        if query is None:
            return json.dumps({})
        tags = json.loads(query.tags)
        for i in tags:
            result[str(i['id'])] = []

        if _event_type in [1012]:
            db_data = eval(event_list[str(_event_type)]['db']).query.order_by('project').all()
            for p in db_data:
                tasks = json.loads(p.tasks)
                if '_tag' in tasks[0]:
                    for i in tasks[0]['_tag']:
                        if str(i) not in result:
                            result[str(i)] = []
                        result[str(i)].append(p.project)
        else:  # default (key: project, data: basic._check_tags)
            db_data = eval(event_list[str(_event_type)]['db']).query.order_by('project').all()
            for p in db_data:
                basic = json.loads(p.basic)
                if '_tag' in basic:
                    for i in basic['_tag']:
                        if str(i) not in result:
                            result[str(i)] = []
                        result[str(i)].append(p.project)


        return json.dumps(result)


    elif _action == 'event_list':
        with open(STATIC_PATH + 'check_tags/event_list.json', encoding='UTF-8') as f:
            event_list = json.load(f)
        return json.dumps(event_list)

    return jsonify(result_data)
